package cn.wsalix.login.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.BasicServiceImpl;
import cn.anlaser.utils.FastJsonMapper;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.biz.service.CategoryService;
import cn.wsalix.login.entity.QQAccessToken;
import cn.wsalix.login.form.QQAccessTokenForm;
import cn.wsalix.login.repository.QQAccessTokenRepository;
import cn.wsalix.login.service.QQAccessTokenService;
import cn.wsalix.observable.service.LoginService;
import cn.wsalix.shiro.token.QQToken;

@Transactional
@Service("qqAccessTokenService")
public class QQAccessTokenServiceImpl
		extends
		BasicServiceImpl<QQAccessTokenForm, QQAccessTokenRepository, QQAccessToken>
		implements QQAccessTokenService {
	@Autowired
	private QQAccessTokenRepository qqAccessTokenRepository;
	@Autowired
	private CategoryService categoryService;

	@Override
	public String module() {
		return "/qq/access_token";
	}

	@Override
	public QQAccessTokenRepository getRepository() {
		return qqAccessTokenRepository;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(QQAccessTokenForm entity) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (entity.getQqUserId() != null && entity.getQqUserId() != 0) {
			filters.put("qqUser.id", new SearchFilter("qqUser.id", Operator.EQ,
					entity.getQqUserId()));
		}
		return filters;
	}

	@Override
	public Class<QQAccessToken> getEntityClazz() {
		return QQAccessToken.class;
	}

	@Transactional
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof LoginService) {
			// UserLoginService userLoginService = (UserLoginService) o;
			if (arg instanceof QQToken) {
				QQToken upToken = (QQToken) arg;
				updateQQAccessToken(upToken);

			}
		}

	}

	private QQAccessToken updateQQAccessToken(QQToken upToken) {
		QQAccessToken qqAccessToken = qqAccessTokenRepository
				.findByOpenId(upToken.getOpenId());
		if (qqAccessToken == null) {
			qqAccessToken = FastJsonMapper.fromJson(upToken.getRemark(),
					QQAccessToken.class);
			add(qqAccessToken);
		}
		return qqAccessToken;
	}
}
